<?php
namespace app\common\model;
use app\common\model\BaseModel;
/**
 * 
 */
class UserModel extends BaseModel
{ 

	public function reg($data)
	{
		// 验证码
		if (!captcha_check($data['captcha'])) {
			$this->error='验证码错误';
			return;
		}
		// 注册IP
		$data=$data+['ip'=>request()->ip()];
		// 密码处理
		$data['password']=$this->makePassword($data['password']);
		$res=$this->validate('User.reg')->isUpdate(false)->allowField(true)->save($data);
		if ($res) {
			return 1;
		}
	}

	public function login($data)
	{
		$where['user_name']=$data['user_name'];
		$where['password']=$this->makePassword($data['password']);
		$user=$this->where($where)->find();
		if ($user) {
			if ($user->status==1) {
				cookie('crt_userid',encrypt($user->id));
				return $user->id;
			}else{
				$this->error='用户被禁用';
				return ;
			}
		}else{
			$this->error='用户不存在';
			return;
		}
	}

	public function edit($id,$data)
	{ 
		$user=$this->find(getCookieUserid());
		$res=$user->validate('User.edit')->isUpdate(true)->allowField(true)->save($data);
		if ($res) {
			return 1;
		}
	}

	// 修改密码
	public function editPwd($id,$password)
	{
		$password=$this->makePassword($password);
		$user=$this->find($id);
		$res=$user->allowField(['password'])->save([
			'password'=>$password
		]);
		if ($res) {
			return 1;
		}
	}

	public function enabled($data=[])
	{
		$user=$this->find($data['id']);
		$res=$user->isUpdate(true)->allowField(true)->save([
			'status'=>1
		]);
		if ($res) {
			$this->msg='启用成功';
			return 1;
		}
	}

	public function makePassword($password){
	    $salt='random_cqz_DBYFYAYBYNAK';
	    $password=md5(md5($password).$salt);
	    return $password;
	}


	public function getGroupIdTextAttr($value,$data)
	{
		$text=db('user_group')->where('id='.$data['group_id'])->value('title');
		return '<span class="color-'.$data['group_id'].'">'.$text.'</span>';
	}

	public function getStatusTextAttr($value,$data)
	{
		$text='正常';
		switch ($data['status']) {
			case '1':
				$text='<span class="label label-success">正常<span>';
				break;
			case '0':
				$text='<span class="label label-danger">已禁用<span>';
				break; 
		}
		return $text;
	}


}